#include "StringUtil.h"
#include <stdarg.h>
#include <windows.h>
using namespace std;

std::string FrameworkStringUtil::format(const char *formatStr, ...)
{
#define CC_MAX_STRING_LENGTH (1024*100)

    std::string ret;

    va_list ap;
    va_start(ap, formatStr);

    char* buf = (char*)malloc(CC_MAX_STRING_LENGTH);

    if(buf != NULL)
    {
        vsnprintf_s(buf, CC_MAX_STRING_LENGTH, CC_MAX_STRING_LENGTH, formatStr, ap);
        ret = buf;
        free(buf);
    }

    va_end(ap);

    return ret;
}


void FrameworkStringUtil::split(const string& src, const string& separator, vector<string>& dest, bool isNull)
{
	string::size_type start = 0, index;
	do
	{
		index = src.find_first_of(separator, start);
		if (index != string::npos)
		{
			std::string substring(src.substr(start, index - start));
			start = index + 1;
			if (isNull&&substring.empty() && substring.length() == 0)
				continue;
			dest.push_back(substring);
		}
	} while (index != string::npos);

	//the last token
	std::string substring(src.substr(start));
	if (isNull&&substring.empty() && substring.length() == 0)
		return;
	dest.push_back(substring);
}


std::string FrameworkStringUtil::trim( std::string& str )
{
	string ret;
	int first = 0;
	size_t last = str.size() - 1;


	 while(str[first] == ' ') {
		 first ++;
		if(first == str.size()) {
			break;
		}

	}

	if(first == str.size()) {
		return "";
	}

	 while(str[last] == ' ') {
		 last --;
		if(last < 0) {
			break;
		}
	}
	return str.substr(first, last - first + 1);
}

int FrameworkStringUtil::unicode2Utf8(const wchar_t* unicode, char* utf8, int nBuffSize)   
{      
	if (!unicode || !wcslen(unicode))  
	{  
		return 0;  
	}  
	int len;      
	len = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, NULL, 0, NULL, NULL);   
	if (len > nBuffSize)  
	{  
		return 0;  
	}    
	WideCharToMultiByte(CP_UTF8, 0, unicode, -1, utf8, len, NULL,NULL);      
	return len;      
}  

std::string FrameworkStringUtil::gb2312ToUtf8( const string& input )
{
	std::string result;
	WCHAR *strSrc;
	char *szRes;

	int i = MultiByteToWideChar(CP_ACP, 0, input.c_str(), -1, NULL, 0);
	strSrc = new WCHAR[i+1];
	MultiByteToWideChar(CP_ACP, 0, input.c_str(), -1, strSrc, i);

	i = WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, NULL, 0, NULL, NULL);
	szRes = new char[i+1];
	memset(szRes, 0, i + 1);
	int j=WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, szRes, i, NULL, NULL);

	result = szRes;
	delete []strSrc;
	delete []szRes;

	return result;

}

